//
//  XSPieView.m
//  Test
//
//  Created by xueshan1 on 2018/12/14.
//  Copyright © 2018 xueshan1. All rights reserved.
//
/*
 原理:
 没有直接画扇形, 还是换画圆环线的方式,
 将'线'的弧形半径设置为扇形r的一半,
 将'线'宽度设置为扇形r的2倍数,
 即可画圆
 
 
 */

#import "XSPieView.h"
#import "UIView+XSLayout.h"

@interface XSPieView ()
{
    CGPoint _center;
}
@property(nonatomic,strong)NSArray<XSPieViewModel *> *dataSource;
@property(nonatomic,strong)NSMutableArray<CAShapeLayer *> *dataLayers;
@property(nonatomic,strong)NSMutableArray<UIView *> *allSubviews;
@property(nonatomic,strong)NSMutableArray *endPercent;
@property(nonatomic,strong)CAShapeLayer *touchLayer;



@end
@implementation XSPieView

- (id)initWithFrame:(CGRect)frame viewType:(XSPieViewType)type{
    self.viewType = type;
    return [self initWithFrame:frame];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initData];
        
    }
    return self;
}

- (void)initData{
    _outCircleRaidus = MIN(self.width, self.height)/2 - 20;
    _arcWidth = 50;
    _canClick = YES;
    
    //
    _dataLayers = [NSMutableArray array];
    _allSubviews = [NSMutableArray array];
    _endPercent = [NSMutableArray array];
    
}

- (void)drawPieViewWithDataSource:(NSArray<XSPieViewModel *> *)dataSource{
    _dataSource = dataSource;
    if (dataSource.count == 0) {
        return;
    }
    
    [self drawPieView];
}
- (void)drawPieView{
    CGFloat sumValue = 0;
    for (XSPieViewModel *model in self.dataSource) {
        sumValue += model.value;
    }
    _center = CGPointMake(self.width/2, self.height/2);
    CGFloat radius = _outCircleRaidus - _arcWidth/2;
    CGFloat start = 0;
    
    if (self.viewType == XSPieViewType_Pie) {
        radius = _outCircleRaidus/2;
        _arcWidth = _outCircleRaidus ;
    }
    
    
    for (int i = 0; i<self.dataSource.count; i++) {
        XSPieViewModel *model = self.dataSource[i];
        CGFloat end = model.value/sumValue + start;
        
        CAShapeLayer *arcLayer = [self arcLayerWithCenter:_center arcRadius:radius arcWidth:_arcWidth fillColor:[UIColor clearColor] strokeColor:model.color startPercent:start endPercent:end];
        [self.layer addSublayer:arcLayer];
        [self.dataLayers addObject:arcLayer];
        
        //记录
        [self.endPercent addObject:@(end)];
        model.startP = start;
        model.endP = end;
        model.percentValue = model.value/sumValue;
        start = end;
    }
    
    [self addAnimation:YES duration:0.5];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self drawLabels];
    });
    
}

- (void)drawLabels{
    for (int i = 0; i<self.dataSource.count; i++) {
        XSPieViewModel *model = self.dataSource[i];
        UILabel *label = [UILabel new];
        label.text = [NSString stringWithFormat:@"%.1f%%",model.percentValue * 100.0];
        [label sizeToFit];
        CGFloat radius = _outCircleRaidus - _arcWidth/2;
        CGFloat angle = (model.startP + (model.endP - model.startP)/2) * M_PI *2;
        CGFloat centerX = _center.x + radius * sin(angle);
        CGFloat centerY = _center.y - radius * cos(angle);
        label.center = CGPointMake(centerX, centerY);
        [self addSubview:label];
        [self.allSubviews addObject:label];
        //        label.backgroundColor = [UIColor yellowColor];
        
    }
    
}

- (CAShapeLayer *)arcLayerWithCenter:(CGPoint)center arcRadius:(CGFloat)radius arcWidth:(CGFloat)arcWidth fillColor:(UIColor *)fillColor strokeColor:(UIColor *)strokeColor startPercent:(CGFloat)startePer endPercent:(CGFloat)endPer{
    UIBezierPath *arcPath = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:-M_PI_2 endAngle:M_PI_2 * 3 clockwise:YES];
    CAShapeLayer *arcLayer = [CAShapeLayer layer];
    arcLayer.lineWidth = arcWidth;
    arcLayer.fillColor = fillColor.CGColor;
    arcLayer.strokeColor = strokeColor.CGColor;
    arcLayer.strokeStart = startePer;
    arcLayer.strokeEnd = endPer;
    arcLayer.path = arcPath.CGPath;
    
    return arcLayer;
}

- (void)addAnimation:(BOOL)animaiton duration:(CGFloat)duration {
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    animation.duration = duration;
    animation.fromValue = @(0);
    animation.toValue = @(1);
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    
    for (CAShapeLayer *layer in self.dataLayers) {
        [layer addAnimation:animation forKey:nil];
    }
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if (!_canClick) {
        return;
    }
 
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];
    CGFloat toCenterLength = sqrtf(powf(location.y - _center.y, 2) + powf(location.x - _center.x, 2));
    if (toCenterLength > _outCircleRaidus || toCenterLength < (_outCircleRaidus - _arcWidth)) {
        return;
    }
    CGFloat anglePercent = [self anglePercenWithCenter:_center fromPoint:location];
    XSPieViewModel *locatioModel = nil;
    for (XSPieViewModel *model in self.dataSource) {
        if (model.endP > anglePercent) {
            locatioModel = model;
            break;
        }
    }
    if (_touchLayer) {
        [_touchLayer removeFromSuperlayer];
        _touchLayer = nil;
    }
  
    _touchLayer = [self arcLayerWithCenter:_center arcRadius:_outCircleRaidus + 5 arcWidth:10 fillColor:[UIColor clearColor] strokeColor:[locatioModel.color colorWithAlphaComponent:0.6] startPercent:locatioModel.startP endPercent:locatioModel.endP];
    [self.layer addSublayer:_touchLayer];
    
    
    
}
//所在角度百分比(?)
- (CGFloat)anglePercenWithCenter:(CGPoint)center fromPoint:(CGPoint)reference {
    CGFloat angleOfLine = atanf((reference.y - center.y) / (reference.x - center.x));
    CGFloat percentage = (angleOfLine + M_PI/2)/(2 * M_PI);
    return (reference.x - center.x) > 0 ? percentage : percentage + .5;
}

@end
